<template>
  <view>
    <view class="xmain">
      <headBar :title="showTitle"></headBar>
      <view class="qtCOntent">
        <view class="qtTitle">
          <view class="uni-flex uni-row">
            <view class="flex-item">
              <view class="selTag" v-if="currentQuestion.answer <= 4">单选</view>
              <view class="selTag" v-else="currentQuestion.answer<4">多选</view>
            </view>
            <view class="flex-item">
              {{ currentQuestion.title }}
            </view>
          </view>
        </view>
        <image :src="currentQuestion.img_url" v-if="currentQuestion.img_url"></image>
        <view class="uni-flex uni-column qtOptions">
          <view class="flex-item flex-item-V  qtOptionsItem" v-for="(item,index) in optionList">
            <view class="uni-flex uni-row" v-if="item.optionTitle" @click="selectAnswer(index)">
              <view class="flex-item xleft">
                <view class="abc" v-if="item.key === '√'" style="background: #0e7b11;color:#FFFFFF;">{{ item.key }}
                </view>
                <view class="abc" v-if="item.key === 'X'" style="background: #9a2037;color:#FFFFFF;">{{ item.key }}
                </view>
                <view class="abc" v-if="item.key === index">{{ item.key }}</view>
              </view>
              <view class="flex-item">
                {{ item.optionTitle }}
              </view>
            </view>
          </view>
        </view>
      </view>
      <view style="height: 40rpx;"></view>
      <view class="qtPreNext uni-flex uni-row">
        <view class="flex-item">
          <view class="uni-flex uni-row">
            <uni-icons type="clear" size="28" color="#ff0000"></uni-icons>
            <view class="flex-item">{{ wrongNum }}</view>
          </view>
        </view>
        <view style="width:30rpx;"></view>
        <view class="flex-item">
          <view class="uni-flex uni-row">
            <uni-icons type="checkbox-filled" size="28" color="#3495fc"></uni-icons>
            <view class="flex-item">{{ rightNum }}</view>
          </view>
        </view>
        <view style="width:30rpx;"></view>
        <view class="flex-item" @click="x_redirect('/pages/collect/lst')">
          <view class="uni-flex uni-row">
            <uni-icons type="star-filled" size="28" color="#db6209"></uni-icons>
            <view class="flex-item">{{ collectNum }}</view>
          </view>
        </view>
      </view>
      <view style="height: 30rpx;"></view>
      <view class="qtPreNext uni-flex uni-row">
        <view class="flex-item">
          <uni-fav @click="dumpPrev()" class="favBtn" :star="false" bg-color="#3495fc" fg-color="#ffffff"
                   :contentText="{contentDefault: '上一题',contentFav: '上一题'}" :circle="true"/>
        </view>
        <view style="width:10rpx;"></view>
        <view class="flex-item">
          <uni-fav @click="dumpNext()" class="favBtn" :star="false" bg-color="#3495fc" fg-color="#ffffff"
                   :contentText="{contentDefault: '下一题',contentFav: '下一题'}" :circle="true"/>
        </view>
        <view style="width:10rpx;"></view>
        <view class="flex-item">
          <uni-fav @click="alertShow = true" class="favBtn" :star="false" bg-color="#3495fc" fg-color="#ffffff"
                   :contentText="{contentDefault: '查看解析',contentFav: '查看解析'}" :circle="true"/>
        </view>
        <view style="width:10rpx;"></view>
        <view class="flex-item">
          <uni-fav @click="doCollect(false)" class="favBtn" :bg-color="collectColor" fg-color="#ffffff"
                   bg-color-checked="#007aff" :contentText="{contentDefault: collectText,contentFav: '已收藏'}"
                   :circle="true"/>
        </view>
        <view style="width:10rpx;"></view>
        <view class="flex-item">
          <uni-fav @click="examineEnd()" class="favBtn" :star="false" bg-color="#3495fc" fg-color="#ffffff"
                   :contentText="{contentDefault: '交卷',contentFav: '交卷'}" :circle="true"/>
        </view>
      </view>
      <xToastCommon v-if="alertShow" :isShow="alertShow"  @hideDialog="handleChangeDialogShow">
        <view class="" style="background: #FFFFFF;border-radius: 10rpx;width:95%;margin: 0rpx auto;padding:10rpx;">
          <uni-section title="题解分析" type="line">
            <view>
              {{ currentQuestion.explains }}
            </view>
          </uni-section>
          <uni-section title="正确答案" type="line">
            <view>
              {{ currentQuestion.answerArr.join() }}
            </view>
          </uni-section>
        </view>
      </xToastCommon>
      <xToastCommon v-if="endShow" :isShow="endShow"  @hideDialog="handleChangeDialogEndShow">
        <view class="" style="background: #FFFFFF;border-radius: 10rpx;width:95%;margin: 0rpx auto;padding:10rpx;">
          <uni-section title="考试结果" type="line">
            <view style="padding-left:40rpx;">
              <view>正确题数：{{rightNum}}</view>
              <view>错误题数：{{wrongNum}}</view>
              <view>考试分数：{{rightNum}}</view>
              <view>考试结果：<text :style="rightNum>90?'color:#3495fc;':'color:#FF0000;'">{{rightNum>90?'及格':'不及格'}}</text></view>
            </view>
          </uni-section>
          <view>
            <view class="uni-flex uni-row">
              <view class="flex-item xnoticeAction">
                <view class="xk_btn" @click="endShow = false">已知晓</view>
              </view>
              <view class="flex-item xnoticeAction"></view>
              <view class="flex-item xnoticeAction">
                <view class="xk_btn xk_btn_active" @click="exmaineRetry()">再来一次</view>
              </view>
            </view>
          </view>
        </view>
      </xToastCommon>
    </view>
    <bootNav nav="examine"></bootNav>
  </view>

</template>

<script>
export default {
  data() {
    return {
      currentIndex: 0,
      currentQuestion: {},
      model: "c1",
      subject: 1,
      cacheKey: "",
      qtPageKey: "",
      optionList: {},
      alertShow: false,
      rightNum: 0,
      wrongNum: 0,
      collectNum: 0,
      isCollect: false,
      collectText: '收藏',
      collectColor: '#dd524d',
      lastTime: 45,
      showTitle:'',
      examineRemainSeconds:2700,
      endShow: false
    }
  },
  onShareAppMessage() {
    return {
      title: this.title,
    }
  },
  onShareTimeline: function () {
    return {
      title: this.title,
    }
  },
  onLoad(e) {
    var t = this;
    if (e.model) {
      t.model = e.model;
    }
    if (e.subject) {
      t.subject = e.subject;
    }
    var cacheExamineRemainSeconds = t.xCacheGet('examineRemainSeconds');
    if(cacheExamineRemainSeconds){
      t.examineRemainSeconds = cacheExamineRemainSeconds;
    }

    //设置缓存索引
    t.setCatchIndex();
    // 获取当前题目
    t.getQuestion();
    // 获取收藏数
    t.doCollect(true);
    //倒计时
    t.countdown(t.examineRemainSeconds);
    //初始化错误和正确的答题数量
    t.doRightNum(false);
    t.doWrongNum(false);
  },
  methods: {
    // 设置缓存索引
    setCatchIndex() {
      var t = this;
      var cacheKey = 'examine_' + t.model + "_" + t.subject;
      t.cacheKey = cacheKey;
      var cacheIndex = cacheKey + "_index";
      var cacheIndexValue = t.xCacheGet(cacheIndex);
      if (cacheIndexValue) {
        t.currentIndex = cacheIndexValue;
      }
    },
    // 初始化题目选项
    initOptionList() {
      var initOptionList = {
        "A": {"key": "A", "optionColumn": "option1", "isRightAnswer": false, "optionTitle": ""},
        "B": {"key": "B", "optionColumn": "option2", "isRightAnswer": false, "optionTitle": ""},
        "C": {"key": "C", "optionColumn": "option3", "isRightAnswer": false, "optionTitle": ""},
        "D": {"key": "D", "optionColumn": "option4", "isRightAnswer": false, "optionTitle": ""}
      };
      var t = this;
      var currentQuestion = t.currentQuestion;
      if (currentQuestion && currentQuestion.optionListActed) {
        t.optionList = currentQuestion.optionListActed;
      } else {
        t.optionList = initOptionList;
      }
      var optionList = t.optionList;
      for (var x in optionList) {
        optionList[x]["optionTitle"] = currentQuestion[optionList[x]['optionColumn']]
        if ((currentQuestion.answerArr) && (currentQuestion.answerArr).includes(x)) {
          optionList[x]["isRightAnswer"] = true;
        }
      }
      t.optionList = optionList;
    },
    currentIndexChange() {
      var t = this;
      var cacheIndex = t.cacheKey + "_index";
      t.xCacheSet(cacheIndex, t.currentIndex);
      t.getQuestion();
    },
    getQuestion() {
      var t = this;
      var currentIndex = t.currentIndex;
      var cachePageKey = t.cacheKey;
      t.qtPageKey = cachePageKey;
      var qtList = t.xCacheGet(cachePageKey);
      if (!qtList) {
        t.getQuestionList();
      } else {
        t.currentQuestion = qtList[currentIndex];
        t.initOptionList();
      }
    },
    getQuestionList() {
      var t = this;
      t.x_request("api/ytjk.data/examine", {
        subject: t.subject,
        model: t.model,
      }, function (t, res) {
        var list = res.data;
        t.xCacheSet(t.qtPageKey, list);
        t.currentQuestion = list[0];
        t.initOptionList();
      })
    },
    selectAnswer(index) {
      var t = this;
      var optionList = t.optionList;
      var isLock = false;
      for (var x in optionList) {
        if (optionList[x]['key'] === 'X') {
          isLock = true;
          break;
        }
      }
      if (!isLock) {
        var selectOption = optionList[index];
        if (selectOption.isRightAnswer) {
          optionList[index]['key'] = '√';
          t.doRight();
        } else {
          optionList[index]['key'] = 'X';
          t.doWrongNum(true);
        }
        //记录操作答案
        t.currentQuestion.optionListActed = optionList;
        var questionList = t.xCacheGet(t.qtPageKey);
        questionList[t.currentIndex] = t.currentQuestion;
        t.xCacheSet(t.qtPageKey, questionList);
      }
    },
    doRight() {
      var t = this;
      var currentQuestion = t.currentQuestion;
      var isDump = 0;//是否要跳转到下一题
      if (currentQuestion.answer <= 4) {
        // 单选，直接跳到下一题
        isDump = 1;
      } else {
        // 多选题继续选择
        var rightNum = 0;
        var optionList = t.optionList;
        for (var x in optionList) {
          if (optionList[x]['key'] === '√') {
            rightNum++;
          }
        }
        if (rightNum === currentQuestion['answerArr'].length) {
          isDump = 1;
        }
      }
      if (isDump === 1) {
        t.doRightNum(true);
        t.dumpNext();
      }
    },
    dumpNext() {
      // 跳转下一题
      var t = this;
      var currentQT = t.currentQuestion;
      if(!currentQT.optionListActed){
        uni.showToast({title: '请先答完该题', icon: 'error', duration: 2000})
      }else{
        var questionList = t.xCacheGet(t.qtPageKey);
        if (t.currentIndex < (questionList.length - 1)) {
          t.currentIndex++;
        } else {
          uni.showToast({title: '已经是最后1题了', icon: 'error', duration: 2000})
        }
        t.currentIndexChange();
        t.alertShow = false;
      }
    },
    dumpPrev() {
      // 跳转上一题
      var t = this;
      if (t.currentIndex > 0) {
        t.currentIndex--;
      } else {
        if (t.currentIndex <= 1) {
          uni.showToast({title: '已经是第1题了', icon: 'error', duration: 2000})
        }
      }
      t.currentIndexChange();
      t.alertShow = false;
    },
    doRightNum(isAdd) {
      var t = this;
      var key = 'examineRightNum';
      var cacheNum = t.xCacheGet(key);
      if(cacheNum){
        t.rightNum = cacheNum;
      }else{
        t.rightNum = 0;
      }
      if(isAdd){
        t.rightNum++;
        t.xCacheSet(key,t.rightNum);
      }
    },
    doWrongNum(isAdd) {
      var t = this;
      var key = 'examineWrongNum';
      var cacheNum = t.xCacheGet(key);
      if(cacheNum){
        t.wrongNum = cacheNum;
      }else{
        t.wrongNum = 0;
      }
      if(isAdd){
        t.wrongNum++;
        t.xCacheSet(key,t.wrongNum);
      }
      if(t.wrongNum >= 10){
          t.examineEnd();
      }
    },
    doCollect(getNum) {
      var t = this;
      var cacheKey = "qtCollected";
      var currentQuestion = t.currentQuestion;
      var id = currentQuestion.question_id;
      var cacheCollectList = t.xCacheGet(cacheKey);
      if (!cacheCollectList) {
        cacheCollectList = {};
      }
      if (!getNum) {
        if (cacheCollectList[id]) {
          delete cacheCollectList[id];
        } else {
          cacheCollectList[id] = currentQuestion;
        }
        t.xCacheSet(cacheKey, cacheCollectList);
      }
      if (!cacheCollectList[id]) {
        t.isCollect = false;
        t.collectText = '收藏';
        t.collectColor = '#666666';
      } else {
        t.isCollect = true;
        t.collectText = '已收藏';
        t.collectColor = '#dd524d';
      }
      var collectNum = Object.keys(cacheCollectList).length;
      t.collectNum = collectNum;
    },
    countdown(seconds) {
      var t = this;
      const intervalId = setInterval(() => {
        if (seconds > 0) {
          seconds--;
          // 将秒数转换为mm:ss格式
          const minutes = Math.floor(seconds / 60).toString().padStart(2, '0');
          const remainingSeconds = (seconds % 60).toString().padStart(2, '0');
          t.showTitle = `倒计时: ${minutes}:${remainingSeconds}`;
          t.xCacheSet('examineRemainSeconds',seconds);
        } else {
          t.examineEnd();
          clearInterval(intervalId);
        }
      }, 1000);
    },
    // 考试结束
    examineEnd(){
      var t = this;
      t.showTitle = '考试结束';
      t.endShow = true;
      t.xCacheSet('examineRemainSeconds',0);
    },
    // 重新考试
    exmaineRetry(){
      var t =this;
      t.xCacheSet(t.qtPageKey,{});
      t.xCacheSet('examineRightNum',0);
      t.xCacheSet('examineWrongNum',0);
      uni.removeStorage({key:t.cacheKey});
      t.x_redirect('/pages/examin/examin?subject='+t.subject);
    },
    handleChangeDialogShow(){
      var t = this;
      t.alertShow = !t.alertShow;
    },
    handleChangeDialogEndShow(){
      var t = this;
      t.endShow = !t.endShow;
    }
  }
}
</script>

<style>
@import "../question/question.css";

</style>
